var publiccode = 'ZGZvI1mi8Q';
var imgHost = 'http://img.artart.cn/';
function formatTime(date, day_join, time_join) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  if(time_join) {
    return [year, month, day].map(formatNumber).join(day_join) + ' ' + [hour, minute, second].map(formatNumber).join(time_join)
  } else {
    return [year, month, day].map(formatNumber).join(day_join)
  }
  
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function api(d){
  if(!d.method)
    d.method="GET";
    var header = d.header ? d.header :{
        "Content-Type": "application/json" 
    };
    if(d.method=="POST" || d.method=="post") {
      d.data = json2Form(d.data);
      header = {
        "Content-Type": "application/x-www-form-urlencoded" 
      };
    }
    console.log("params ", d.data);
  wx.request({
    url:"https://api.artart.cn/api.php",
    method:d.method,
    data:d.data,
    success: function(responseData){
      if(responseData.statusCode == 200){
        d.success(responseData);
      }
    },
    header: header,  
    fail: function(e) {
      if(d.fail){
        e.fail(e);
      }
      console.log(e);
    }
  });
}

function json2Form(json) {  
    var str = [];  
    for(var p in json){  
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));  
    }  
    return str.join("&");  
}

function isString(str){
  return (typeof str == 'string') && str.constructor == String; 
}

module.exports = {
  formatTime: formatTime,
  api:api,
  json2Form:json2Form,
  publiccode:publiccode,
  imgHost: imgHost,
  isString:isString
}
